package lab.anoper.juc.threadlocal;

import java.time.Instant;

/**
 * @author 闫家洪（yanjiahong@vcredit.com）
 * @since 2024/12/12
 */
public class WebSessionDemo {
    static class RequestInfo {
        private Long userId;
        private String requestId;
        private Instant startTime;

        public RequestInfo(Long userId, String requestId, Instant startTime) {
            this.userId = userId;
            this.requestId = requestId;
            this.startTime = startTime;
        }

        @Override
        public String toString() {
            return userId + " " + requestId + " " + startTime;
        }
    }

    static final class SessionManager {
        private static final ThreadLocal<RequestInfo> requestInfoTl = ThreadLocal.withInitial(() -> null);

        public static void setRequestInfo(Long userId, String requestId, Instant startTime) {
            requestInfoTl.set(new RequestInfo(userId, requestId, startTime));
        }

        public static RequestInfo getRequestInfo() {
            return requestInfoTl.get();
        }

        public static void clear() {
            requestInfoTl.remove();
        }
    }

    public static void main(String[] args) {
        Runnable r1 = () -> {
            SessionManager.setRequestInfo(1L, "request-1", Instant.now());
            System.out.println(SessionManager.getRequestInfo());
        };
        Runnable r2 = () -> {
            SessionManager.setRequestInfo(2L, "request-2", Instant.now());
            System.out.println(SessionManager.getRequestInfo());
        };
        Runnable r3 = () -> {
            SessionManager.setRequestInfo(3L, "request-3", Instant.now());
            System.out.println(SessionManager.getRequestInfo());
        };
        new Thread(r1).start();
        new Thread(r2).start();
        new Thread(r3).start();
    }
}















